// src/stores/chat.store.ts
import { defineStore } from 'pinia';

// Define message structure (should match the one in useMessage.ts or a shared type)
interface ChatMessage {
  id: string;
  roomId: string;
  senderId: string;
  content: string;
  timestamp: number;
  // Add other relevant fields
}

interface ChatState {
  // Store messages in an object keyed by roomId
  rooms: Record<string, { messages: ChatMessage[] }>;
  currentRoomId: string | null;
}

export const useChatStore = defineStore('chat', {
  state: (): ChatState => ({
    rooms: {},
    currentRoomId: null,
  }),
  getters: {
    // Get messages for the current room or a specific room
    getMessagesByRoom: (state) => (roomId: string): ChatMessage[] => {
      return state.rooms[roomId]?.messages || [];
    },
    // Get messages for the currently active room
    getCurrentRoomMessages: (state): ChatMessage[] => {
      if (!state.currentRoomId) return [];
      return state.rooms[state.currentRoomId]?.messages || [];
    },
  },
  actions: {
    // Initialize or clear messages for a specific room
    initRoom(roomId: string) {
        if (!this.rooms[roomId]) {
            this.rooms[roomId] = { messages: [] };
        }
    },
    // Set all messages for a specific room (e.g., after fetching history)
    setMessages(roomId: string, messages: ChatMessage[]) {
      if (!this.rooms[roomId]) {
        this.initRoom(roomId);
      }
      this.rooms[roomId].messages = messages;
    },
    // Add a single message to the correct room
    addMessage(message: ChatMessage) {
      const { roomId } = message;
      if (!roomId) {
        console.error('Message missing roomId:', message);
        return;
      }
      if (!this.rooms[roomId]) {
        this.initRoom(roomId);
      }
      // Avoid adding duplicate messages (optional, based on ID)
      if (!this.rooms[roomId].messages.some(m => m.id === message.id)) {
         this.rooms[roomId].messages.push(message);
         // Optional: Keep messages sorted by timestamp
         this.rooms[roomId].messages.sort((a, b) => a.timestamp - b.timestamp);
      }
    },
    // Set the currently active room
    setCurrentRoom(roomId: string | null) {
      this.currentRoomId = roomId;
      if (roomId && !this.rooms[roomId]) {
        this.initRoom(roomId); // Ensure room state exists when switching
      }
    },
    // Clear all chat state (e.g., on logout)
    clearChatState() {
      this.rooms = {};
      this.currentRoomId = null;
    },
  },
});